﻿using JWTWebApi.Models;
using JWTWebApi.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace JWTWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize] // 整个控制器需要认证
    public class OrderController : ControllerBase
    {
        private readonly ILogger<OrderController> _logger;

        public OrderController(ILogger<OrderController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 根据订单ID获取订单信息
        /// </summary>
        /// <param name="id">订单ID</param>
        /// <returns>订单对象</returns>
        [HttpGet]
        [EndpointSummary("根据订单ID获取订单信息")]
        public OrderData Get(int id)
        {
            _logger.LogInformation("开始获取订单信息，订单ID: {OrderId}", id);
            
            try
            {
                // 从JWT Claims中获取用户名
                string customerName = HttpContext.User.FindFirst(ClaimTypes.Name)?.Value ?? "未知用户";
                // 解析JWT Token获取用户信息
                JwtTokenModel tokenModel = JwtHelper.ParsingJwtToken(HttpContext);
                string tokenUserName = tokenModel?.UserName ?? "未知用户";
                
                _logger.LogDebug("用户信息 - Claims用户名: {CustomerName}, Token用户名: {TokenUserName}", customerName, tokenUserName);
                
                OrderData order = new OrderData
                {
                    OrderId = id,
                    CustomerId = id + 1,
                    CustomerName = customerName,
                    TokenUserName = tokenUserName,
                    OrderDate = DateTime.Now,
                    TotalAmount = 110d,
                    Status = "运输途中"
                };
                
                _logger.LogInformation("成功获取订单信息，订单ID: {OrderId}, 客户: {CustomerName}", id, customerName);
                return order;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取订单信息时发生错误，订单ID: {OrderId}", id);
                throw;
            }
        }

        /// <summary>
        /// 异步上传图片方法
        /// </summary>
        /// <param name="file">要上传的文件，类型为IFormFile，表示通过表单提交的文件</param>
        /// <returns>返回一个布尔值，表示上传是否成功</returns>
        [HttpPost]
        [EndpointSummary("异步上传图片方法")]
        [EndpointDescription("图片上传接口")]
        [DisableRequestSizeLimit]
        public async Task<IActionResult> UploadImgageAsync(IFormFile file)
        {
            _logger.LogInformation("开始上传文件，文件名: {FileName}, 文件大小: {FileSize} bytes", 
                file?.FileName ?? "未知", file?.Length ?? 0);
            
            try
            {
                if (file == null || file.Length == 0)
                {
                    _logger.LogWarning("上传失败：没有文件上传或文件为空");
                    return BadRequest("没有文件上传");
                }

                // 清理文件名，防止路径遍历攻击
                var fileName = Path.GetFileName(file.FileName);
                if (string.IsNullOrEmpty(fileName))
                {
                    _logger.LogWarning("上传失败：无效的文件名 - {OriginalFileName}", file.FileName);
                    return BadRequest("无效的文件名");
                }
                
                var filePath = Path.Combine("Uploads", fileName);
                _logger.LogDebug("文件将保存到路径: {FilePath}", filePath);

                using (var stream = System.IO.File.Create(filePath))
                {
                    await file.CopyToAsync(stream);
                }
                
                _logger.LogInformation("文件上传成功 - 文件名: {FileName}, 大小: {FileSize} bytes, 保存路径: {FilePath}", 
                    fileName, file.Length, filePath);
                
                return Ok(new { FileName = fileName, Size = file.Length });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "文件上传时发生错误 - 文件名: {FileName}", file?.FileName ?? "未知");
                return StatusCode(500, "服务器错误");
            }
        }
    }
}
